package com.person.jc.web.login;

import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.person.jc.common.Constants;
import com.person.jc.entity.TsUser;
import com.person.jc.interceptor.LoginInterceptor;
import com.person.jc.service.security.TsUserService;
import com.person.jc.service.security.TsVisitLogService;
import com.person.jc.utils.Utils;

import java.util.UUID;

@Clear({LoginInterceptor.class})
public class LoginController extends Controller {
	
	public void index() {
		TsUser tsUser = (TsUser)getSessionAttr(Constants.LOGIN_USER);
		if(tsUser == null){
			render("login/login.jsp");
		}else{
			redirect("/success");
		}
	}
	
	public void login(){
		String username = getPara("username");
		String password = getPara("password");
		TsUser tsUser = TsUserService.me.getUserById(username);
		boolean loginFlag = false;
		if(tsUser == null){
			setAttr("promt", "用户名不存在");
		}else if(!password.equals(tsUser.getPassword())){
			setAttr("promt", "用户名或密码错误");
		}else if("0".equals(tsUser.getStatus())){
			setAttr("promt", "账号已停用");
		}else{
			setSessionAttr(Constants.LOGIN_USER, tsUser);
			setSessionAttr(Constants.LOGIN_IP, Utils.getIpAddr(getRequest()));
//			setCookie(Constants.LOGIN_USER, UUID.randomUUID().toString(),36000,true);
			loginFlag = true;
			TsVisitLogService.me.saveLoginInfo(tsUser, Utils.getIpAddr(getRequest()), getSession().getId());
		}
		if(loginFlag){
			redirect("/success");
		}else{
			render("login/login.jsp");
		}
	}
	
	public void logouts(){
		TsVisitLogService.me.updateLoginInfo(getSession().getId());
		removeSessionAttr(Constants.LOGIN_USER);
		render("login/login.jsp");
	}
	
}
